package com.yn.bsc.web;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.base.Strings;
import com.yn.bsc.core.Result;
import com.yn.bsc.model.UserInfo;

/**
 * 用户登录处理
 * 
 * @ClassName LoginController
 * @author z
 * @date 2017年9月20日 上午10:21:25
 */
@Controller
public class LoginController {

	/* 日志处理 */
	private Logger log = Logger.getLogger(this.getClass().getName());

	/**
	 * 用户登录跳转
	 * 
	 * @return String @throws
	 */
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String loginForm(Model model) {
		return "login";
	}

	/**
	 * 用户登录请求
	 * 
	 * @return Result @throws
	 */
	@RequestMapping(value = "login", method = RequestMethod.POST)
	@ResponseBody
	public Result login(String account, String password, Model model) {
		log.info("登录用户：" + account);
		Result result = new Result();
		if (Strings.isNullOrEmpty(account)) {
			result.setSuccess(false);
			result.setCode(9001);
			result.setData(null);
			result.setMessage("用户名不能为空!");
			return result;
		}
		if (Strings.isNullOrEmpty(account)) {
			result.setSuccess(false);
			result.setCode(9001);
			result.setData(null);
			result.setMessage("密码不能为空!");
			return result;
		}
		try {
			password = new Md5Hash(password).toHex().trim();
			UsernamePasswordToken token = new UsernamePasswordToken(account, password);
			// ShiroToken token = new ShiroToken(username, password);
			SecurityUtils.getSubject().login(token);
			UserInfo shiroUser = (UserInfo) SecurityUtils.getSubject().getPrincipal();

			result.setSuccess(true);
			result.setCode(200);
			result.setData(shiroUser);
			result.setMessage("登陆成功!");

		} catch (Exception e) {
			result.setSuccess(false);
			result.setCode(9001);
			result.setData(null);
			result.setMessage("登陆异常!" + e.getMessage());
		}
		return result;
	}

	/**
	 * 用户退出登录 @return String @throws
	 */
	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public Result logout(RedirectAttributes redirectAttributes) {
		// 使用权限管理工具进行用户的退出，跳出登录，给出提示信息
		SecurityUtils.getSubject().logout();
		Result result = new Result();
		result.setSuccess(true);
		result.setCode(200);
		result.setMessage("您已安全退出!");

		return result;
	}

}
